package io.gitee.sfch.chunmi.springframework;

import io.gitee.sfch.chunmi.exception.BusinessException;
import io.gitee.sfch.chunmi.entity.Response;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 全局异常处理器，若业务需要覆盖异常处理，可通过{@link Order} 使用优先级进行覆盖
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 未知异常：未预期的异常，这部分异常需要深入进行排查，并修复或改造为系统异常，建议记录到日志、系统日志表以方便排查
    // 系统异常，一般是系统出错、错误调用、代码错误等导致的异常等，建议记录到日志、系统日志表以方便排查：参数错误、连接超时等
    // 业务异常，由于业务引起的异常，是系统可容忍的异常，这部分异常不需要打印堆栈，可能不记录日志：状态已变更、库存为0等

    /**
     * 系统未知异常，返回500
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response<String> handleUnknownException(Exception ex) {
        log.error(ex.getMessage(), ex);
        return Response.failEmpty("系统未知异常，请联系管理员");
    }

    /**
     * 业务异常，返回200。业务上的状态校验、内部库存校验等，虽然业务上失败，但是对于系统而言是一个成功的请求。
     */
    @ExceptionHandler(BusinessException.class)
    public Response<String> handleBusinessException(BusinessException ex) {
        log.error("[{}] {}", ex.getClass().getSimpleName(), ex.getMessage());
        return Response.failEmpty(ex.getMessage());
    }

    /**
     * 未匹配资源，访问根目录时，若没有静态资源，会报该错误；但是在将spring.web.resources.add-mappings设置为false时，
     * 该捕获由于被NoHandlerFoundException覆盖将不再生效
     */
    @ExceptionHandler(NoResourceFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response<String> handleNoResourceFoundException(NoResourceFoundException ex) {
        log.error(ex.getMessage());
        return Response.failEmpty("404 Not Found");
    }

    /**
     * 未匹配路径，访问一个不存在的API时，会报该错误
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response<String> handleNotHandlerFoundException(NoHandlerFoundException ignore) {
        // 异常会在PageNoFound进行打印，这里就不需要二次打印
        return Response.failEmpty("404 Not Found");
    }

    /**
     * 请求方法不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Response<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        return Response.failEmpty(ex.getMessage());
    }

    /**
     * 请求校验异常，返回400
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Response<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        StringJoiner errorMessageJoiner = new StringJoiner(", ");
        BindingResult bindingResult = ex.getBindingResult();
        // 不明
        List<ObjectError> globalErrors = bindingResult.getGlobalErrors();
        for (ObjectError globalError : globalErrors) {
            errorMessageJoiner.add(globalError.getDefaultMessage());
        }
        // userName不能为空
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            errorMessageJoiner.add(fieldError.getField() + fieldError.getDefaultMessage());
        }
        return Response.failEmpty(errorMessageJoiner.toString());
    }

    /**
     * 处理路径变量/请求参数校验异常，返回400
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleConstraintViolationExceptions(ConstraintViolationException ex) {
        String errorMessage = ex.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }
}
